package repository

import (
	"goscan-mgt/model"
	"goscan-mgt/utils"

	"gorm.io/gorm"
)

// ProjectRepository 结构体定义
type ProjectRepository struct {
	db *gorm.DB // 数据库连接
}

// NewProjectRepository 创建新的ProjectRepository实例
func NewProjectRepository() *ProjectRepository {
	db := utils.GetDB() // 获取数据库连接
	return &ProjectRepository{db: db}
}

// Create 创建新的项目
func (r *ProjectRepository) Create(project *model.Project) error {
	return r.db.Create(project).Error
}

// GetByID 根据ID获取项目
func (r *ProjectRepository) GetByID(id uint) (*model.Project, error) {
	var project model.Project
	err := r.db.First(&project, id).Error
	return &project, err
}

// Update 更新项目
func (r *ProjectRepository) Update(project *model.Project) error {
	return r.db.Save(project).Error
}

// UpdateStatusToOneExceptID 将除指定ID外，所有Status为0的项目的Status更新为1
func (r *ProjectRepository) UpdateStatusToOneExceptID(id uint) error {
	return r.db.Model(&model.Project{}).
		Where("id <> ? AND status = ?", id, 0).
		Update("status", 1).Error
}
func (r *ProjectRepository) Delete(id uint) error {
	return r.db.Delete(&model.Project{}, id).Error
}

// FindByName 根据项目名称查找项目
func (r *ProjectRepository) FindByName(name string) ([]model.Project, error) {
	var projects []model.Project
	err := r.db.Where("project_name like ?", name).Order("id desc").Find(&projects).Error
	return projects, err
}

// GetAll 获取所有项目
func (r *ProjectRepository) GetAll() ([]model.Project, error) {
	var projects []model.Project
	err := r.db.Order("id desc").Find(&projects).Error
	return projects, err
}

// GetPaginated 获取分页项目列表
func (r *ProjectRepository) GetPaginated(page int, pageSize int) (*utils.Pagination[model.Project], error) {
	dbModel := r.db.Model(&model.Project{}).Order("id desc")
	result, err := utils.NewPagination[model.Project](page, pageSize, dbModel)
	return result, err
}
